/**
 * 连接管理器
 * 负责管理活跃的HTTP和HTTPS连接
 */
export class ConnectionManager {
  constructor() {
    this.activeConnections = new Set();
    this.activeHttpsConnections = new Set();
    
    // 系统测试域名过滤
    this.systemTestDomains = [
      'msftconnecttest.com',
      'ipv6.msftconnecttest.com',
      'connectivitycheck.gstatic.com',
      'clients3.google.com',
      'detectportal.firefox.com',
      'nmcheck.gnome.org'
    ];
  }

  /**
   * 添加HTTP连接
   */
  addHttpConnection(socket) {
    this.activeConnections.add(socket);
    socket.on('close', () => {
      this.activeConnections.delete(socket);
    });
    socket.on('error', () => {
      this.activeConnections.delete(socket);
    });
  }

  /**
   * 添加HTTPS连接
   */
  addHttpsConnection(socket) {
    this.activeHttpsConnections.add(socket);
    socket.on('close', () => {
      this.activeHttpsConnections.delete(socket);
    });
    socket.on('error', () => {
      this.activeHttpsConnections.delete(socket);
    });
  }

  /**
   * 强制关闭所有活跃连接
   */
  async forceCloseAllConnections() {
    try {
      const httpConnections = this.activeConnections.size;
      const httpsConnections = this.activeHttpsConnections.size;
      
      if (httpConnections > 0 || httpsConnections > 0) {
        console.log(`🔌 强制关闭活跃连接: HTTP=${httpConnections}, HTTPS=${httpsConnections}`);
        
        // 强制关闭所有HTTP连接
        for (const socket of this.activeConnections) {
          try {
            socket.destroy();
          } catch (error) {
            console.warn('⚠️ 关闭HTTP连接失败:', error.message);
          }
        }
        
        // 强制关闭所有HTTPS连接
        for (const socket of this.activeHttpsConnections) {
          try {
            socket.destroy();
          } catch (error) {
            console.warn('⚠️ 关闭HTTPS连接失败:', error.message);
          }
        }
        
        // 等待连接关闭
        await new Promise(resolve => setTimeout(resolve, 1000));
        console.log('✅ 所有活跃连接已强制关闭');
      } else {
        console.log('ℹ️ 没有活跃连接需要关闭');
      }
      
    } catch (error) {
      console.error('❌ 强制关闭连接失败:', error.message);
    }
  }

  /**
   * 同步强制关闭所有连接
   */
  forceCloseAllConnectionsSync() {
    try {
      // 强制关闭所有HTTP连接
      for (const socket of this.activeConnections) {
        try {
          socket.destroy();
        } catch (error) {
          // 忽略错误
        }
      }
      
      // 强制关闭所有HTTPS连接
      for (const socket of this.activeHttpsConnections) {
        try {
          socket.destroy();
        } catch (error) {
          // 忽略错误
        }
      }
      
    } catch (error) {
      console.error('❌ 同步强制关闭连接失败:', error.message);
    }
  }

  /**
   * 清理所有连接追踪
   */
  clearAll() {
    this.activeConnections.clear();
    this.activeHttpsConnections.clear();
  }

  /**
   * 检查是否为系统测试请求
   */
  isSystemTestRequest(url) {
    try {
      const urlObj = new URL(url);
      const hostname = urlObj.hostname.toLowerCase();
      
      return this.systemTestDomains.some(domain => 
        hostname === domain || hostname.endsWith('.' + domain)
      );
    } catch (error) {
      return false;
    }
  }

  /**
   * 获取连接统计信息
   */
  getStats() {
    return {
      activeHttpConnections: this.activeConnections.size,
      activeHttpsConnections: this.activeHttpsConnections.size,
      totalActiveConnections: this.activeConnections.size + this.activeHttpsConnections.size
    };
  }
} 